package org.example.service.impl;

import cn.jbit.pojo.Order;
import com.google.gson.Gson;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.example.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.Future;

/**
 * @author 张在成
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RestTemplate restTemplate;


    @HystrixCollapser(batchMethod = "selOrderListByIds",
    scope = com.netflix.hystrix.HystrixCollapser.Scope.GLOBAL,
    collapserProperties = {
            //间隔多久的请求会进行合并，默认10ms
            @HystrixProperty(name = "timerDelayInMilliseconds",value = "20"),
            //批处理之前，批处理中心允许请求的最大请求数
            @HystrixProperty(name = "maxRequestsInBatch",value = "200")
    })
    @Override
    public Future<Order> selectOrderByOrderId(Integer orderId) throws Exception {
        System.out.println("----orderService----selectOrderByOrderId");
        return null;
    }

//  @Cacheable(cacheNames = "orderService:user:all")
    @Override
    public List<Order> getOrderList() {
        List<Order> list = restTemplate.getForObject("http://order-service-feign/orderListRemote/", List.class);
        return list;
    }

//    @Cacheable(cacheNames = "orderService:user:order-Ids")
    @HystrixCommand   //需要容错的方法
    @Override
    public List<Order> selOrderListByIds(List<Integer> list) {
        System.out.println("----orderService----selOrderListByIds");
        Gson gson=new Gson();
        //设置请求头
        HttpHeaders headers = new HttpHeaders();
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());
        //将list转换为json
        String json = gson.toJson(list);
        System.out.println(json);
        HttpEntity<String> formEntity = new HttpEntity<String>(json, headers);
        List list1 = restTemplate.postForObject("http://order-service-feign/orderRemoteIds?" + list, formEntity, List.class);
        return list1;
    }
}
